#include "Config.h"
#include "tinyxml.h"

Config::Config()
{

}

Config::~Config()
{

}

Config* Config::configWithFile( const char * file )
{
	Config * database = new Config();
	if (database && database->init(file))
	{
		database->autorelease();
		return database;
	}
	CC_SAFE_DELETE(database);
	return NULL;

}

Config* Config::configWithXml( TiXmlElement* xml )
{
	Config * database = new Config();
	if (database && database->init(xml))
	{
		database->autorelease();
		return database;
	}
	CC_SAFE_DELETE(database);
	return NULL;
}

bool	Config::init( TiXmlElement * xml )
{
	TiXmlElement * elem = xml->FirstChildElement();
	TiXmlAttribute * att = NULL;
	while( elem )
	{
		DataItem dataItem;
		att = elem->FirstAttribute();

		const char * key = att->Value();

		while( att )
		{
			dataItem.insert( StrPair(att->Name(), att->Value()) );
			att = att->Next();
		}

		m_table.insert(StrDataItemPair(key,dataItem));

		elem = elem->NextSiblingElement();
	}

	return true;
}

bool Config::init( const char * file )
{
	bool ret = true;
	TiXmlDocument * doc = new TiXmlDocument();
	
	if( doc->LoadFile(file) )
	{
		init(doc->RootElement());
	}
	else
	{
		ret = false;
	}

	CC_SAFE_DELETE( doc );
	return ret;
}

const Config::DataItem& Config::operator[]( const string& key )
{
	return getItem(key);
}
const Config::DataItem&		Config::operator[](const string& key) const
{
	return getItem(key);
}
const Config::DataItem& Config::getItem( const string&key )
{
	const DataItem * ret = NULL;

	if( m_table.find(key)!=m_table.end())
	{
		ret = &m_table[key];
	}

	return *ret;
}
const Config::DataItem& Config::getItem( const string&key ) const
{
	const DataItem * ret = NULL;
	DataTable::const_iterator it = m_table.find(key);

	if( it!=m_table.end())
	{
		ret = &(it->second);
	}

	return *ret;
}

Config::DataTable&	Config::getItems()
{
	return m_table;
}



